import React, {useState} from "react";
import {useNavigate} from 'react-router-dom'
import axios from "axios";

const Login = () => {
    const navigate = useNavigate()

    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");

    //登录
    const handleSubmit = async (event: React.FormEvent) => {
        event.preventDefault();
        try {
            const response = await axios.post("http://localhost:5000/giveALike/login", {
                username,
                password,
            });
            if (response.status == 200) {
                //登录成功，跳转首页
                navigate('/home');
                //将用户信息存到session
                window.sessionStorage.setItem("user", JSON.stringify(response.data))
            } else {
                alert(response.data.message)
            }
        } catch (error) { /* empty */
        }
    };

    return (
        <form onSubmit={handleSubmit}>
            <div>
                <label htmlFor="username">Username</label>
                <input
                    type="text"
                    id="username"
                    value={username}
                    onChange={(event) => setUsername(event.target.value)}
                />
            </div>
            <div>
                <label htmlFor="password">Password</label>
                <input
                    type="password"
                    id="password"
                    value={password}
                    onChange={(event) => setPassword(event.target.value)}
                />
            </div>
            <button type="submit">Login</button>
        </form>
    );
};

export default Login;
